<template>
  <el-dialog
    :title="title"
    :before-close="handleCancel"
    :visible.sync="dialogVisible"
    width="60%"
  >
    <el-tag
      >如分配给这个人权限，需要先分配他父级（父查看以后才可以看到子集）</el-tag
    >
    <el-row :gutter="20">
      <el-col :span="12">
        <span>人员选择</span>
        <el-tree
          class="tree-border"
          :data="deptOptions1"
          show-checkbox
          default-expand-all
          ref="dept1"
          node-key="id"
          :check-strictly="!form.deptCheckStrictly1"
          empty-text="加载中，请稍候"
          :props="defaultProps"
        ></el-tree>
      </el-col>
      <el-col :span="12">
        <span>文件选择</span>
        <el-tree
          class="tree-border"
          :data="deptOptions"
          show-checkbox
          default-expand-all
          ref="dept"
          node-key="id"
          :check-strictly="!form.deptCheckStrictly"
          empty-text="加载中，请稍候"
          :props="defaultProps"
        ></el-tree>
      </el-col>
    </el-row>

    <!-- 权限选择部分 -->
    <span>权限选择部分</span>
    <el-form :model="form" label-width="120px">
      <el-form-item label="查看权限" prop="fileReadState">
        <el-switch
          v-model="form.fileReadState"
          :active-value="1"
          :inactive-value="0"
        ></el-switch>
      </el-form-item>
      <el-form-item label="修改权限" prop="fileWriteState">
        <el-switch
          v-model="form.fileWriteState"
          :active-value="1"
          :inactive-value="0"
        ></el-switch>
      </el-form-item>
      <el-form-item label="删除权限" prop="fileDeleteState">
        <el-switch
          v-model="form.fileDeleteState"
          :active-value="1"
          :inactive-value="0"
        ></el-switch>
      </el-form-item>
      <el-form-item label="管理权限" prop="fileManageState">
        <el-switch
          v-model="form.fileManageState"
          :active-value="1"
          :inactive-value="0"
        ></el-switch>
      </el-form-item>
    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="handleConfirm">确 认</el-button>
      <el-button @click="handleCancel()">取 消</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { listUser } from '@/api/system/user';
import { addPermission } from '@/api/file/permission';
export default {
  data() {
    return {
      title: '个人权限配置',
      dialogVisible: false,
      // 部门列表
      deptOptions: [],
      deptOptions1: [],
      form: {
        deptCheckStrictly: false,
        deptCheckStrictly1: false,
        fileReadState: 0, // 读取权限，默认未选择
        fileWriteState: 0, // 写入权限，默认未选择
        fileDeleteState: 0, // 删除权限，默认未选择
        fileManageState: 0, // 管理权限，默认未选择
      },
      defaultProps: {
        children: 'children',
        label: 'label',
      },
    };
  },
  methods: {
    init(row) {
      this.deptOptions = [];
      this.deptOptions1 = [];
      this.dialogVisible = true;
      this.getUserList();
      this.getFileList(row);
    },
    async getUserList() {
      try {
        const res = await listUser({
          pageNum: 1,
          pageSize: 100,
        });

        const filteredUsers = res.rows
          .filter((item) => item.userId !== 1)
          .map((item) => ({
            label: item.userName,
            id: item.userId,
            ...item,
          }));

        this.deptOptions1.push(...filteredUsers);
      } catch (error) {
        console.error('获取用户列表失败:', error);
      }
    },
    getFileList(row) {
      this.deptOptions = [
        {
          label: row.fileName,
          id: row.fileId,
          children: parseFileList(row.filePath),
        },
      ];
      parseFileList(row.filePath);
      function parseFileList(fileUrls) {
        const urls = fileUrls.split(',');
        const fileList = urls.map((url, index) => {
          const fileName = url.split('/').pop();
          const fileExtension = fileName.split('.').pop();
          const nameWithoutExtension = fileName
            .split('.')
            .slice(0, -1)
            .join('.');
          const match = url.match(/[^/]+\.[^/]+$/);
          return {
            label: match[0],
            id: index,
            name1: nameWithoutExtension,
            type: fileExtension,
            url: url,
          };
        });

        return fileList;
      }
    },
    handleCancel() {
      this.deptOptions = [];
      this.deptOptions1 = [];
      this.dialogVisible = false;
    },
    async handleConfirm() {
      const selectedUserIds = this.$refs.dept1.getCheckedKeys();
      const selectedFileIds = this.$refs.dept.getCheckedKeys();
      if (selectedUserIds.length === 0 || selectedFileIds.length === 0) {
        this.$message.error('请选择人员和文件');
        return;
      }

      // 提交权限数据
      await addPermission({
        userId: selectedUserIds,
        fileId: selectedFileIds[0],
        fileReadState: this.form.fileReadState,
        fileWriteState: this.form.fileWriteState,
        fileDeleteState: this.form.fileDeleteState,
        fileManageState: this.form.fileManageState,
      });

      this.dialogVisible = false;
    },
  },
};
</script>

<style lang="less" scoped>
.dialog-footer {
  display: flex;
  justify-content: center;
}
/deep/ .el-tree {
  padding: 10px;

  .el-tree-node__label {
    white-space: normal;
    word-break: break-all;
  }
}
</style>
